<template>
  <div class="job-positions-container">
    <div class="header">
      <div class="left">
        <h2>岗位申请</h2>
      </div>
      <div class="right">
        <el-select
          v-model="categoryId"
          placeholder="岗位分类"
          clearable
          @change="handleCategoryChange"
          class="category-filter"
        >
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
        <el-input
          v-model="searchQuery"
          placeholder="搜索岗位标题"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <div class="positions-grid">
      <el-card
        v-for="position in positions"
        :key="position.id"
        class="position-card"
        :body-style="{ padding: '0px' }"
      >
        <div class="position-header">
          <h3>{{ position.title }}</h3>
          <el-tag size="small">{{ position.category.name }}</el-tag>
        </div>
        <div class="position-content">
          <div class="info-row">
            <div class="info-item">
              <el-icon><Money /></el-icon>
              <span>¥{{ position.salary }}/小时</span>
            </div>
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>招聘{{ position.quota }}人</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <el-icon><Location /></el-icon>
              <span>{{ position.workLocation }}</span>
            </div>
            <div class="info-item">
              <el-icon><Timer /></el-icon>
              <span>{{ position.workingHours }}</span>
            </div>
          </div>
          <div class="description">
            {{ position.description }}
          </div>
          <div class="teacher-info">
            <span>发布教师：{{ position.teacher.name }}</span>
            <span>发布时间：{{ formatDate(position.createTime) }}</span>
          </div>
        </div>
        <div class="position-footer">
          <el-button type="primary" @click="handleApply(position)">申请岗位</el-button>
        </div>
      </el-card>
    </div>

    <div v-if="!loading && (!positions || positions.length === 0)" class="empty-data">
      <el-empty description="暂无岗位" />
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 申请对话框 -->
    <el-dialog
      title="岗位申请"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="简历" prop="resumeUrl">
          <el-upload
            class="upload-demo"
            :http-request="customUpload"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
          >
            <el-button type="primary">上传简历</el-button>
            <el-button v-if="form.resumeUrl" type="success" plain>已上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 pdf/doc/docx 文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="求职信" prop="coverLetter">
          <el-input
            v-model="form.coverLetter"
            type="textarea"
            :rows="4"
            placeholder="请简要介绍自己，说明为什么想申请这个岗位"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          提交申请
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Money, User, Location, Timer } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getAvailablePositions, applyPosition } from '@/api/student/jobPosition'
import { getCategories } from '@/api/common/jobCategory'
import { uploadFile } from '@/api/common/upload'
import { formatDate } from '@/utils/format'

// 列表数据
const loading = ref(false)
const positions = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const searchQuery = ref('')
const categoryId = ref(null)
const categories = ref([])

// 表单数据
const dialogVisible = ref(false)
const formRef = ref(null)
const submitting = ref(false)
const selectedPosition = ref(null)

const form = ref({
  resumeUrl: '',
  coverLetter: ''
})

// 表单验证规则
const rules = {
  resumeUrl: [
    { required: true, message: '请上传简历', trigger: 'change' }
  ],
  coverLetter: [
    { required: true, message: '请填写求职信', trigger: 'blur' }
  ]
}

// 获取岗位列表
const fetchPositions = async () => {
  try {
    loading.value = true
    const response = await getAvailablePositions({
      page: currentPage.value - 1,
      size: pageSize.value,
      categoryId: categoryId.value,
      search: searchQuery.value
    })
    
    if (response) {
      positions.value = response.content
      total.value = response.totalElements
    }
  } catch (error) {
    console.error('Failed to fetch positions:', error)
    ElMessage.error('获取岗位列表失败')
  } finally {
    loading.value = false
  }
}

// 获取岗位分类
const fetchCategories = async () => {
  try {
    const response = await getCategories()
    if (response) {
      categories.value = response
    }
  } catch (error) {
    console.error('Failed to fetch categories:', error)
    ElMessage.error('获取岗位分类失败')
  }
}

// 处理分类筛选
const handleCategoryChange = () => {
  currentPage.value = 1
  fetchPositions()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPositions()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPositions()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPositions()
}

// 处理申请
const handleApply = (position) => {
  selectedPosition.value = position
  form.value = {
    resumeUrl: '',
    coverLetter: ''
  }
  dialogVisible.value = true
}

// 自定义上传方法
const customUpload = async (options) => {
  try {
    const response = await uploadFile(options.file)
    options.onSuccess(response)
  } catch (error) {
    options.onError(error)
  }
}

// 处理文件上传成功
const handleUploadSuccess = (response) => {
  form.value.resumeUrl = response.url
  ElMessage.success('简历上传成功')
}

const beforeUpload = (file) => {
  const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('只能上传 PDF/DOC/DOCX 格式的文件')
    return false
  }
  return true
}

// 提交申请
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    await applyPosition(selectedPosition.value.id, form.value)
    ElMessage.success('申请成功')
    dialogVisible.value = false
  } catch (error) {
    console.error('Application submission failed:', error)
    ElMessage.error(error.response?.data || '申请失败')
  } finally {
    submitting.value = false
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchCategories()
  fetchPositions()
})
</script>

<style scoped>
.job-positions-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right {
  display: flex;
  gap: 16px;
}

.category-filter {
  width: 150px;
}

.search-input {
  width: 300px;
}

.positions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.position-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.position-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.position-header h3 {
  margin: 0;
  font-size: 16px;
}

.position-content {
  padding: 15px;
  flex: 1;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.description {
  margin: 15px 0;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.teacher-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  color: #999;
  font-size: 12px;
}

.position-footer {
  padding: 15px;
  border-top: 1px solid #eee;
  text-align: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}
</style> 